package com.albert.myauth.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/auth")
public class AuthController {

    @RequestMapping(value = "/get_token")
    public String getToken() {
        String ak = "zlf";
        String sk = "sk123";
        String token = JWT.create().withAudience(ak)
                .sign(Algorithm.HMAC256(sk));
        return token;
    }

    @RequestMapping(value = "/token_verify")
    public String verifyToken(String token) {
        String ak = JWT.decode(token).getAudience().get(0);
        //根据ak去获取sk
        String sk = "sk123";
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(sk)).build();
        try {
            jwtVerifier.verify(token);
            return "true";
        } catch (JWTVerificationException e) {
            throw new RuntimeException("401");
        }
    }
}
